<template>
  <el-dialog
    v-model="dialogVisible"
    :close-on-click-modal="false"
    append-to-body
    title="新建任务"
    width="650"
    class="dialogForm"
    :before-close="beforeClose"
  >
    <el-form
      :model="formParams"
      :rules="rulesForm"
      label-width="110px"
      ref="ruleFormRef"
    >
      <el-form-item label="任务标题" prop="title">
        <el-input
          v-model="formParams.title"
          placeholder="请输入任务标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="formParams.startTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择时间"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="formParams.endTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择时间"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="关联项目">
        <el-select
          v-model="formParams.businessType"
          placeholder="项目类型"
          clearable
          style="width: 30%; margin-right: 2%"
          @change="changeBusinessType"
          :disabled="isBusinessType"
        >
          <el-option
            v-for="item in rsgl_associated_item"
            :label="item.label"
            :value="item.value"
            :key="item.value"
          ></el-option>
        </el-select>
        <el-select
          v-model="formParams.businessId"
          placeholder="请输入"
          filterable
          remote
          :remote-method="queryProject"
          @change="changeBusinessId"
          clearable
          style="width: 68%"
          :disabled="isDisabled"
        >
          <el-option
            v-for="item in optionsProjectName"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="问题类型" prop="questionType" v-if="isQuestionType">
        <el-select
          v-model="formParams.questionType"
          placeholder="问题类型"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="item in rsgl_question_type"
            :label="item.label"
            :value="item.value"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="负责人员" prop="directorId">
        <el-select
          clearable
          v-model="formParams.directorId"
          placeholder="请选择负责人员"
          @focus="userInputFocus"
          class="w-full"
        >
          <el-option
            v-for="(item, index) in selectOptionObj['directorId']"
            :key="index"
            :label="item.label"
            :value="item.uuid"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="参与人员">
        <el-select
          clearable
          v-model="formParams.playersId"
          placeholder="请选则参与人员"
          @focus="participateIdFocus"
          class="w-full"
          multiple
        >
          <el-option
            v-for="(item, index) in selectOptionObj['playersId']"
            :key="index"
            :label="item.label"
            :value="item.uuid"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="紧要程度" prop="impSign">
        <el-radio-group
          v-model="formParams.impSign"
          @change="radioClick($event)"
        >
          <template v-for="(item, index) in rsgl_urgent_status" :key="index">
            <el-radio-button :label="item.value" :value="item.value">{{
              item.label
            }}</el-radio-button>
          </template>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item label="任务提醒">
        <el-select
          v-model="formParams.serviceType"
          placeholder="请选择任务提醒"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="item in task_reminder_time"
            :label="item.label"
            :value="item.value"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="提醒方式">
        <el-checkbox-group v-model="formParams.reminderMethod">
          <template v-for="(item, index) in reminder_method" :key="index">
            <el-checkbox :label="item.value" :value="item.value">{{
              item.label
            }}</el-checkbox>
          </template>
        </el-checkbox-group>
      </el-form-item> -->
      <el-form-item label="任务描述">
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入任务描述"
          v-model="formParams.remark"
          maxlength="200"
          show-word-limit
        >
        </el-input>
      </el-form-item>
      <el-form-item label="上传附件：">
        <el-upload
          v-model:file-list="formParams.fileList"
          class="upload-demo"
          action="#"
          :before-upload="beforeAvatarUpload"
          :http-request="handleFileChange"
          accept=".rar, .zip, .doc, .docx, .pdf"
          :show-file-list="false"
          style="margin-right: 6px"
        >
          <el-button type="default" style="font-size: 14px"
            ><el-icon><UploadFilled /></el-icon>上传文件</el-button
          >
          <template #tip>
            <div class="el-upload__tip float-right">
              支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过20MB
            </div>
          </template>
        </el-upload>
        <div class="text-14px mt-10px" style="width: 100%">
          <div v-for="(item, index) in fileList" :key="item.fileId">
            <a :href="item.url" target="_blank" class="text-#409eff">{{
              item.origFileName
            }}</a>
            <el-button text plain @click="delFileName(index)">删除</el-button>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="beforeClose">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="btnLoading">
          保 存
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 弹出框下拉框 -->
  <SelectDialog
    :dialog-param="dialogParam"
    @ok="selectDialogData"
    @close="closeFn"
  ></SelectDialog>
</template>
<script setup name="addTaskManage">
import { addManage } from '@/api/system/notice'
import {
  addTaskList,
  getTaskDetail,
  getOrdinnerorder,
  getOrdpurchaseorder
} from '@/api/taskManage/task'
import { getTreeNodeByParam, getUniqueUserId } from '@/utils/commo'
import { ref, reactive, computed, getCurrentInstance, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import useCommonStore from '@/store/modules/common'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import { getOrdprojectNoPriv } from '@/api/projectManage/project' //项目模糊搜索
import { getOrderList } from '@/api/salesManage/contractManage' //订单模糊搜索
import { getListByCustomerName } from '@/api/customerManage/customerList' //企业客户模糊搜索
import { getBusinessOpportunityListSelect } from '@/api/salesManage/businessManage' //商机模糊搜索
import { getDetailTactlistByCactName } from '@/api/customerManage/customerList' //联系人模糊搜索
const { proxy } = getCurrentInstance()
const userStore = useUserStore()
const dialogVisible = ref(false)
/*** 文件上传 start */
let fileList = ref([])
//当前时间
const gettime = ref('')
// 通用数据store
const router = useRouter()
const route = useRoute()
const commonStore = useCommonStore()
const {
  task_reminder_time, //任务提醒
  rsgl_urgent_status, //紧要程度
  rsgl_task_status,
  sys_service_type,
  reminder_method, //提醒方式
  rsgl_associated_item, //项目类型
  rsgl_question_type //问题类型
} = proxy.useDict(
  'task_reminder_time',
  'rsgl_urgent_status',
  'rsgl_task_status',
  'sys_service_type',
  'reminder_method',
  'rsgl_associated_item',
  'rsgl_question_type'
)
const isDisabled = ref(true)
const isBusinessType = ref(false)
const isQuestionType = ref(false)
const data = reactive({
  formParams: {
    title: null,
    startTime: null,
    endTime: null,
    impSign: '3',
    directorId: null, //负责人
    playersId: null, //参与人员
    serviceType: null, //任务提醒
    reminderMethod: '0', //提醒方式
    remark: null,
    businessType: null,
    businessName: null,
    businessId: null,
    filePath: [],
    fileName: [] //文件名
  },
  selectOptionObj: {}, // 参与人员
  dialogParam: {},
  optionsProjectName: [], //关联项目
  optionsOrder: [], //关联订单
  // 表单校验
  rulesForm: {
    title: [{ required: true, message: '任务标题不能为空', trigger: 'blur' }],
    startTime: [
      { required: true, message: '开始时间不能为空', trigger: 'blur' }
    ],
    endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
    directorId: [
      { required: true, message: '负责人员不能为空', trigger: 'blur' }
    ]
  }
})
const {
  formParams,
  selectOptionObj,
  dialogParam,
  rulesForm,
  optionsProjectName
} = toRefs(data)
const props = defineProps({
  // 弹出框是否显示
  dialogParam: {
    required: true
  }
})
watch(
  () => props.dialogParam,
  val => {
    if (JSON.stringify(props.dialogParam) != '{}') {
      console.log('props.dialogParam', props.dialogParam)
      if (props.dialogParam.businessType) {
        isBusinessType.value = true
      }
      init()
    }
  },
  {
    deep: true,
    immediate: true
  }
)
function init() {
  dialogVisible.value = props.dialogParam.isVisible
  optionsProjectName.value = [
    {
      label: props.dialogParam.businessName,
      value: props.dialogParam.businessId
    }
  ]
  formParams.value = JSON.parse(JSON.stringify(props.dialogParam))
  //    formParams.value = { ...formParams.value, ...props.dialogParam }
  formParams.value.impSign = '3'
  getTime()
}
init()
//关联项目类型
function changeBusinessId(val) {
  formParams.value.businessName = optionsProjectName.value.find(
    item => item.value == val
  )
    ? optionsProjectName.value.find(item => item.value == val).label
    : '--'
}
//关联项目
function changeBusinessType(item) {
  optionsProjectName.value = []
  formParams.value.businessId = ''
  if (formParams.value.businessType) {
    isDisabled.value = false
    if (formParams.value.businessType == '1') {
      isQuestionType.value = true
    } else {
      isQuestionType.value = false
    }
  } else {
    isDisabled.value = true
  }
}
//关联项目名称
async function queryProject(val) {
  optionsProjectName.value = []
  switch (formParams.value.businessType) {
    case '1': //项目
      const proList = await getOrdprojectNoPriv({
        proName: val,
        pageSize: 20
      })
      if (proList.code === 200) {
        optionsProjectName.value = (proList.rows || []).map(v => ({
          label: v.proName,
          value: v.projectId
        }))
      }
      break
    case '2': //销售订单
      const orderList = await getOrderList({
        title: val,
        pageSize: 20
      })
      if (orderList.code === 200) {
        optionsProjectName.value = (orderList.rows || []).map(v => ({
          label: v.title,
          value: v.id
        }))
      }
      break
    case '3': //客户
      const customerList = await getListByCustomerName({
        customer: val,
        pageSize: 20
      })
      if (customerList.code === 200) {
        optionsProjectName.value = (customerList.data || []).map(v => ({
          label: v.customerName,
          value: v.id
        }))
      }
      break
    case '4': //商机
      const businessList = await getBusinessOpportunityListSelect({
        keyword: val,
        pageSize: 20,
        pageNum: 1
      })
      if (businessList.code === 200) {
        optionsProjectName.value = (businessList.rows || []).map(v => ({
          label: v.titleName,
          value: v.id
        }))
      }
      break
    case '5': //联系人
      const contactsNameList = await getDetailTactlistByCactName({
        pageSize: 20,
        entId: '',
        contactName: val
      })
      if (contactsNameList.code === 200) {
        optionsProjectName.value = (contactsNameList.data || []).map(v => ({
          label: v.contactName,
          value: v.id
        }))
      }
      break
    case '6': //采购订单
      const ordpurchaseorderList = await getOrdpurchaseorder({
        title: val,
        pageSize: 20
      })
      if (ordpurchaseorderList.code === 200) {
        optionsProjectName.value = (ordpurchaseorderList.rows || []).map(v => ({
          label: v.title,
          value: v.id
        }))
      }
      break
    case '7': //内部订单
      const ordinonerorderList = await getOrdinnerorder({
        title: val,
        pageSize: 20
      })
      if (ordinonerorderList.code === 200) {
        optionsProjectName.value = (ordinonerorderList.rows || []).map(v => ({
          label: v.title,
          value: v.id
        }))
      }
      break
  }
}
const btnLoading = ref(false) //按钮加载状态
const emit = defineEmits(['closeDialog'])
//关闭
function beforeClose() {
  formParams.value = {}
  fileList.value = []
  emit('closeDialog', 'task')
  // proxy.$emit('closeDialog', 'task')
}
/**
 * 弹出框关闭
 * @param {*} val
 */
const closeFn = val => {
  dialogParam.value.isDialog = false
}
/**
 * 参与人获取焦点事件
 */
function participateIdFocus() {
  const user = useUserStore().user['orgId']
  dialogParam.value = {
    type: 'playersId',
    title: '请选择参与人员',
    dataType: 'person',
    nodeKey: 'uuid',
    multiple: true,
    checkStrictly: false
    // defaultCheckedKeys:[100]
  }
  dialogParam.value.isDialog = true
  dialogParam.value.apiParams = {
    disabled: 'false',
    deptId: user == '484' ? '100' : user
    // deptId:'484'
  }
  dialogParam.value.defaultCheckedKeys = [formParams.value.playersId] || []
}

/**
 * 负责人获取焦点事件
 */
function userInputFocus() {
  console.log('userStore', userStore)
  const user = useUserStore().user['orgId']
  dialogParam.value = {
    type: 'directorId',
    title: '请选择负责人员',
    dataType: 'person',
    nodeKey: 'uuid',
    multiple: false,
    checkStrictly: false
  }
  dialogParam.value.isDialog = true
  dialogParam.value.apiParams = {
    // disabled: 'false',
    deptId: user == '484' ? '100' : user
    // deptId:'484'
  }

  dialogParam.value.defaultCheckedKeys = [formParams.value.directorId] || []
}
/** 弹出框下拉框
 * 负责人
 * @param {*} val  selectDialog组件返回的值
 */
const selectDialogData = val => {
  switch (val.type) {
    case 'directorId':
      console.log('directorId===val', val)
      selectOptionObj.value['directorId'] = val.selectData
      formParams.value.director = val.labelData.toString()
      formParams.value.directorId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : ''
      break
    case 'playersId':
      selectOptionObj.value['playersId'] = val.selectData
      formParams.value.players = val.labelData.toString()
      formParams.value.playersId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys
        : ''
      break
  }
}

const radioClick = tab => {
  console.log('点击了', tab)
}
//获取当前时间
function getTime() {
  var _this = this
  let yy = new Date().getFullYear()
  var mm =
    new Date().getMonth() > 9
      ? new Date().getMonth() + 1
      : new Date().getMonth() == 9
      ? new Date().getMonth() + 1
      : '0' + (new Date().getMonth() + 1)
  var dd =
    new Date().getDate() < 10
      ? '0' + new Date().getDate()
      : new Date().getDate()
  let hh = new Date().getHours()
  let mf =
    new Date().getMinutes() < 10
      ? '0' + new Date().getMinutes()
      : new Date().getMinutes()
  let ss =
    new Date().getSeconds() < 10
      ? '0' + new Date().getSeconds()
      : new Date().getSeconds()
  gettime.value = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
}

//保存
async function handleSubmit() {
  proxy.$refs['ruleFormRef'].validate(valid => {
    if (valid) {
      //   data.playersId = []
      let data = JSON.parse(JSON.stringify(formParams.value))
      data.fileName = []
      data.filePath = []
      delete data.fileList
      console.log('data=====111', data)
      if (formParams.value.directorId) {
        // 获取查询到的user数据对象
        let userObj = getUniqueUserId(
          selectOptionObj.value['directorId'],
          formParams.value.directorId
        )
        //获取userid
        data.directorId = userObj.id
      }
      if (data.playersId) {
        for (let i = 0; i < data.playersId.length; i++) {
          data.playersId[i] = data.playersId[i].replace('U', '')
        }
      }
      data.playersId = data.playersId ? data.playersId.toString() : ''
      //   data.reminderMethod = data.reminderMethod ? data.reminderMethod.toString() : ''

      if (fileList.value.length > 0) {
        for (let i = 0; i < fileList.value.length; i++) {
          data.fileName.push(fileList.value[i].origFileName)
          data.filePath.push(fileList.value[i].url)
        }
      }
      data.fileName = data.fileName ? data.fileName.toString() : ''
      data.filePath = data.filePath ? data.filePath.toString() : ''
      btnLoading.value = true
      addTaskList(data).then(res => {
        if (res.code === 200) {
          btnLoading.value = false
          proxy.$modal.msgSuccess('添加成功!')
          for (let i = 0; i < res.data.length; i++) {
            let mesVoData = {
              businessId: '任务-通知-' + res.data[i].operateId, //业务ID
              content: `${data.title}:${data.remark}`,
              followDate: undefined, //跟进日期
              followType: undefined, //跟进方式
              impSign: data.impSign, //重要程度:0-非常重要，1-重要，2-一般
              receiver: res.data[i].belongId, //接收人id
              receiverName: res.data[i].belongName, //接收人中文
              reminderMethod: '0', //提醒方式:0-系统站内，1-邮箱，2-短信，允许多个并存，例如:0,1,2
              sendTime: gettime.value, //发送时间
              sender: userStore.user.nickName, //发送人
              title: `任务管理:'${data.title}'的消息`, //待办标题
              type: 0, //待办类型:0-普通，1-流程
              serviceType: '1', //服务类型 1-准时提醒
              urgFlag: '2', //紧急程度:0-非常紧急，1-紧急，2-一般
              urlName: '前往处理', //待办链接名称(多链接名称用英文逗号隔开)
              url: `/rsgl/other/taskProcessing?id=${res.data[i].taskId}&operateId=${res.data[i].operateId}` //待办链接(多链接用英文逗号隔开)
            }
            console.log('mesVoData====>', mesVoData)
            addManage(mesVoData).then(res => {})
          }
          beforeClose()
          proxy.$emit('refreshList')
        } else {
          btnLoading.value = false
        }
      })
    }
  })
}
/**文件上传 限制条件**/
function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
}
// 上传附件
async function handleFileChange(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
    }
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
//删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
</script>

<style lang="scss">
.dialogForm {
  .el-dialog__header {
    @apply mr-0  text-#666 font-semibold bg-#f5f5f5;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
  }
  .el-dialog__body {
    padding-right: 40px;
  }
  .footer {
    @apply text-right border-t border-t-solid border-gray-100 pt-20px mt-20px;
  }
}
</style>
